var http = require('http');
var finalhandler = require('finalhandler')
var Router=require('./router/index');
var query=require('./middleware/query');
var middleware =require('./middleware/init');
exports.init=function(){
    console.log('init')
    this.cache={};
    this.settings={};
    //创建Router 函数赋值_router
    this.lazyrouter();
}
exports.lazyrouter=function(){
    if(!this._router){
        this._router=Router({
        })
        this._router.use(query({}));
        this._router.use(middleware.init(this))
    }
}
//添加stack 返回route
exports.route=function(path){
    return this._router.route(path);
}
exports.listen=function(){
    //这里的this访问的是express 里app函数
    var server=http.createServer(this);
    return server.listen.apply(server,arguments);
}
//http 回调函数 执行_router.handle 循环stack
exports.handle=function(req,res,next){
    console.log('1 application.handle',req.url ,req.params,req.baseUrl)
    var router = this._router;//函数
    //http 参数只有req,res 这里的next 为undefined
    var done=next || finalhandler(req,res);
    //console.log(done.toString() )
    if(!router){
        done()
        return ;
    }       
    router.handle(req,res,done);
}
exports.get=function(path){
    console.log('application.get',path,Array.prototype.slice.call(arguments,1))
    var route=this.route(path);
    route.get.apply(route,Array.prototype.slice.call(arguments,1));
    return this;
}
